package com.starblink.android.basic.util.post

import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.fragment.app.FragmentActivity
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.R
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.toastSuccess
import com.starblink.android.basic.ext.toastUI
import com.starblink.android.basic.extension.navigation
import com.starblink.android.basic.network.base.BaseApiCodeAndUrl
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.bus.bean.CollectWishListEvent
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.bus.bean.FollowUserEvent
import com.starblink.android.basic.util.bus.bean.LikePostEvent
import com.starblink.android.basic.util.bus.bean.SubscribeBrandEvent
import com.starblink.android.basic.widget.ConfirmDialog2
import com.starblink.android.basic.widget.dialog.SubscribeDialog
import com.starblink.android.basic.widget.dialog.SubscribeFailDialog
import com.starblink.basic.apollo.ext.ApolloExt.findErrorCode
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.CheckUtil
import com.starblink.basic.util.FastUtil
import com.starblink.rocketreserver.CancelCollectWishListMutation
import com.starblink.rocketreserver.CancelCollectionProductMutation
import com.starblink.rocketreserver.CancelFollowAccountMutation
import com.starblink.rocketreserver.CancelLikeContentMutation
import com.starblink.rocketreserver.CancelLikePostCommentMutation
import com.starblink.rocketreserver.CancelSubscribeMerchantWebMutation
import com.starblink.rocketreserver.CollectWishListMutation
import com.starblink.rocketreserver.CollectionProductMutation
import com.starblink.rocketreserver.FetchSubscriptionSettingQuery
import com.starblink.rocketreserver.FollowAccountMutation
import com.starblink.rocketreserver.LikeContentMutation
import com.starblink.rocketreserver.LikePostCommentMutation
import com.starblink.rocketreserver.ModifySubscriptionSettingMutation
import com.starblink.rocketreserver.MyDeviceSubscribeStaticQuery
import com.starblink.rocketreserver.SubscribeBrandMutation
import com.starblink.rocketreserver.SubscribeMerchantWebV2Mutation
import com.starblink.rocketreserver.UnsubscribeBrandMutation
import com.starblink.rocketreserver.fragment.BrandVOF
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.rocketreserver.fragment.WishListF
import com.starblink.rocketreserver.type.SubscriptionSettingReq
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

object CommonMutateManage {

    /**
     * 统一调用收藏心愿单接口
     * @param wishList 心愿单
     * @param resultCallback 返回接口调用结果，true表示操作成功，false表示操作失败
     */
    fun collectWishlist(
        context: Context,
        wishList: WishListF,
        scope: CoroutineScope = MainScope(),
        resultCallback: ((
            result: Boolean,
        ) -> Unit)? = null,
    ) {
        scope.launch {
            if (!wishList.collectStatus) {//收藏
                val response = SkGqlClient.skMutation(
                    CollectWishListMutation(wishListId = wishList.id)
                )

                if (response?.errors != null) {
                    if (response.findErrorCode(BaseApiCodeAndUrl.CODE_311015001)) {
//                        val contentBinding =
//                            AddVWishlistFailBinding.inflate(
//                                LayoutInflater.from(context),
//                                null,
//                                false
//                            )
//                        val subFailDialog =
//                            CustomDialog.Builder(if (context is Activity) context else ActivityStackManage.currentActivity())
//                                .create(contentBinding.root)
//                        subFailDialog.show()
//                        contentBinding.tryIt.click {
//                            subFailDialog.dismiss()
//                            context.navigation(path = RoutePage.Login.SING_IN)
//                        }
                        val activity = ActivityStackManage.currentActivity()
                        if (activity is FragmentActivity) {
                            SubscribeFailDialog(
                                activity,
                                "Failed to Save",
                                R.mipmap.icon_subscribe_fail_good,
                                R.string.subscribe_fail_good
                            ) {
                                context.navigation(path = RoutePage.Login.SING_IN)
                            }.show(activity.supportFragmentManager, "subscribeFail")
                        }
                    }
                } else {
                    // 发通知，主页Wishlist页面需要监听通知，更新数据，个人中心-客态-Wishlist-Borads需要监听，修改保存状态
                    resultCallback?.invoke(response?.data?.collectWishList == true)
                    if (response?.data?.collectWishList == true) {
                        toastUI("Board saved successfully")
                        FlowBus.with<CollectWishListEvent>(FlowConst.COLLECT_WISHLIST_EVENT)
                            .post(
                                CollectWishListEvent(
                                    wishlistAccountId = wishList.accountInfo.accountF.id,
                                    wishlistId = wishList.id,
                                    latestCollectStatus = true
                                )
                            )
                    }
                }
            } else {//取消收藏
                val response = SkGqlClient.skMutation(
                    CancelCollectWishListMutation(wishListId = wishList.id)
                )
                resultCallback?.invoke(response?.data?.cancelCollectWishList == true)
                if (response?.data?.cancelCollectWishList == true) {
                    toastUI("Board removed successfully")
                    FlowBus.with<CollectWishListEvent>(FlowConst.COLLECT_WISHLIST_EVENT)
                        .post(
                            CollectWishListEvent(
                                wishlistAccountId = wishList.accountInfo.accountF.id,
                                wishlistId = wishList.id,
                                latestCollectStatus = false
                            )
                        )
                }
            }
        }
    }

    /**
     * 统一调用收藏商品接口
     * refreshState 登录成功时先改变状态
     * resultCallback 接口成功回调
     */
    fun collectProduct(
        showDialog: Boolean = false,
        ctx: Context,
        id: String,
        type: Int,//商品 1 标品2
        collected: Boolean,
        scope: CoroutineScope = MainScope(),
        postEvent: Boolean = true,
        refreshState: (() -> Unit)? = null,
        resultCallback: ((
            result: Boolean,
            collected: Boolean,
        ) -> Unit)? = null,
    ) {
//        LoginCheckInterceptor.check2Login(ctx) {

        scope.launch {
            if (!collected) {//收藏
                val response = SkGqlClient.skMutation(
                    CollectionProductMutation(
                        id, type, outOfferId = Optional.present(null)
                    ),
                    showDefaultLoading = false,
                    ifNeedHiddenLoading = false
                )
                if (response?.errors != null) {
                    if (response.findErrorCode(BaseApiCodeAndUrl.CODE_311015001)) {
//                        val contentBinding =
//                            AddVWishlistFailBinding.inflate(
//                                LayoutInflater.from(ctx),
//                                null,
//                                false
//                            )
//                        val subFailDialog =
//                            CustomDialog.Builder(if (ctx is Activity) ctx else ActivityStackManage.currentActivity())
//                                .create(contentBinding.root)
//                        subFailDialog.show()
//                        contentBinding.tryIt.click {
//                            subFailDialog.dismiss()
//                            ctx.navigation(path = RoutePage.Login.SING_IN)
//                        }
                        val activity = ActivityStackManage.currentActivity()
                        if (activity is FragmentActivity) {
                            SubscribeFailDialog(
                                activity,
                                "Failed to Save",
                                R.mipmap.icon_subscribe_fail_good,
                                R.string.subscribe_fail_good
                            ) {
                                ctx.navigation(path = RoutePage.Login.SING_IN)
                            }.show(activity.supportFragmentManager, "subscribeFail")
                        }
                    }
                } else {
                    refreshState?.invoke()
                    if (response?.data?.collectionProduct == true && postEvent) {
                        val collectProductEvent = CollectProductEvent(id, true)
                        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT)
                            .post(collectProductEvent)
                        MainScope().launch {
                            FlowBus.boolFlowBusNotify(FlowConst.OTHER_ADD_PRODUCT_VIEW)
                        }
                        //跨进程通知
                        BridgeUtil.sendFlowBus(FlowConst.COLLECT_PRODUCT_EVENT, collectProductEvent)
                        BridgeUtil.sendFlowBus(FlowConst.OTHER_ADD_PRODUCT_VIEW)
                    }
                    //V1.5.2新逻辑
                    doGuideLogin(
                        3, scope,
                        toastMsg = "Saved Successfully",
                        title = "Item Saved",
                        imageResource = R.mipmap.icon_subscribe_success_good,
                        emailTipResource = R.string.subscribe_success_email_good,
                        noEmailTipResource = R.string.subscribe_success_no_email_good,
                        remindMeKey = UserDataCenter.subscribeRemindMe_Good
                    ) {
                        //弹框取消回调 这里会回调显示 Add to Board
                        resultCallback?.invoke(response?.data?.collectionProduct == true, true)
                    }

                }

            } else {//取消收藏
                val response = SkGqlClient.skMutation(
                    CancelCollectionProductMutation(
                        id, type,
                    ),showDefaultLoading = false
                )
                refreshState?.invoke()
                resultCallback?.invoke(response?.data?.cancelCollectionProduct == true, false)
                if (response?.data?.cancelCollectionProduct == true && postEvent) {
                    val collectProductEvent = CollectProductEvent(id, false)
                    FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT)
                        .post(collectProductEvent)
                    MainScope().launch {
                        FlowBus.boolFlowBusNotify(FlowConst.OTHER_ADD_PRODUCT_VIEW)
                    }
                    //跨进程通知
                    BridgeUtil.sendFlowBus(FlowConst.COLLECT_PRODUCT_EVENT, collectProductEvent)
                    BridgeUtil.sendFlowBus(FlowConst.OTHER_ADD_PRODUCT_VIEW)
                }
            }
        }
//        }
    }

    /**
     * 统一调用点赞接口
     * refreshState 登录成功时先改变状态
     * resultCallback 接口成功回调
     * @param posterId 发布用户ID
     */
    fun likePost(
        ctx: Context,
        postId: String,
        contentType: String?,
        posterId: String,
        like: Boolean,
        likeCount: Int,
        refreshState: () -> Unit,
        resultCallback: (like: Boolean, likeCount: Int) -> Unit,
    ) {
        LoginCheckInterceptor.check2Login(ctx) {
            refreshState()
            CoroutineScope(Dispatchers.IO).launch {
                var res = like
                var count = likeCount
                if (!like) {
                    val response = SkGqlClient.skMutation(
                        LikeContentMutation(postId)
                    )
                    if (response?.data != null && response.data!!.likeContent != null && response.data!!.likeContent == true) {
                        res = !like
                        count += 1
                        AppsflyerManager.reportContentLike(
                            mapOf(
                                "af_content_id" to postId,
                                "af_content_type" to (contentType ?: "1"),
                            )
                        )
                    }

                    MainScope().launch {
                        resultCallback(res, count)
                    }
                    //刷新点赞数据
                    FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT)
                        .post(LikePostEvent(postId, posterId, res, count))
                } else {
                    val response = SkGqlClient.skMutation(
                        CancelLikeContentMutation(postId)
                    )
                    if (response?.data != null && response.data!!.cancelLikeContent != null && response.data!!.cancelLikeContent == true) {
                        res = !like
                        count -= 1
                        AppsflyerManager.reportContentLike(
                            mapOf(
                                "af_content_id" to postId,
                                "af_content_type" to (contentType ?: "1"),
                            )
                        )
                    }
                    MainScope().launch {
                        resultCallback(res, count)
                    }
                    //刷新点赞数据
                    FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT)
                        .post(LikePostEvent(postId, posterId, res, count))
                }
                Log.e("ApolloValSetExt", "===11==$res====$count")
            }
        }
    }

    /**
     * 统一调用点赞评论接口
     * refreshState 登录成功时先改变状态
     * resultCallback 接口成功回调
     */
    fun likePostComment(
        ctx: Context,
        postCommentId: String,
        like: Boolean,
        likeCount: Int,
        refreshState: (
        ) -> Unit,
        resultCallback: (
            like: Boolean,
            likeCount: Int,
        ) -> Unit,
    ) {
        LoginCheckInterceptor.check2Login(ctx) {
            refreshState()
            CoroutineScope(Dispatchers.IO).launch {
                var res = like
                if (!like) {
                    val response = SkGqlClient.skMutation(
                        LikePostCommentMutation(postCommentId)
                    )
                    if (response?.data != null && response.data!!.likePostComment != null && response.data!!.likePostComment) {
                        res = !like
                    }
                    MainScope().launch {
                        resultCallback(res, likeCount + 1)
                    }

                } else {
                    val response = SkGqlClient.skMutation(
                        CancelLikePostCommentMutation(postCommentId)
                    )
                    if (response?.data != null && response.data!!.cancelLikePostComment != null && response.data!!.cancelLikePostComment) {
                        res = !like
                    }
                    MainScope().launch {
                        resultCallback(res, likeCount - 1)
                    }
                }
            }
        }
    }

    /**
     * 统一调用关注用户接口
     * refreshState 登录成功时先改变状态
     * resultCallback 接口成功回调
     */
    fun followUser(
        ctx: Context,
        userId: String,
        followState: Int,
        refreshState: (
        ) -> Unit,
        resultCallback: (
            relationCode: Int,
        ) -> Unit,
    ) {
        LoginCheckInterceptor.check2Login(ctx) {
            refreshState()
            CoroutineScope(Dispatchers.IO).launch {
                var res = followState
                if (!PostUtils.followed(followState)) {
                    val response = SkGqlClient.skMutation(
                        FollowAccountMutation(userId)
                    )
                    if (response?.data != null && response.data!!.followAccount != null
                    ) {
                        res = response.data!!.followAccount
                        // 关注成功，发送通知
                        FlowBus.with<FollowUserEvent>(FlowConst.FOLLOW_USER_EVENT)
                            .post(FollowUserEvent(userId, res))
                        toastUI("Following")
                        AppsflyerManager.reportFollow()
                    }
                    MainScope().launch {
                        resultCallback(res)
                    }

                } else {
                    val response = SkGqlClient.skMutation(
                        CancelFollowAccountMutation(userId)
                    )
                    if (response?.data != null && response.data!!.cancelFollowAccount != null
                    ) {
                        res = response.data!!.cancelFollowAccount
                        // 取消关注成功，发送通知
                        FlowBus.with<FollowUserEvent>(FlowConst.FOLLOW_USER_EVENT)
                            .post(FollowUserEvent(userId, res))
                        toastUI("Unfollowed")
                        AppsflyerManager.reportFollow()
                    }
                    MainScope().launch {
                        resultCallback(res)
                    }
                }
            }
        }
    }

    /**
     * 关注 or 取关店铺
     */
    fun subscribeOrNotMerchant(
        ctx: Context,
        merchantId: String,
        merchantName: String?,
        subOrNot: Boolean,
        scope: CoroutineScope = MainScope(),
        cancelNotCallback: (() -> Unit)? = null,
        refreshState: (() -> Unit)? = null,
        resultCallback: ((success: Boolean) -> Unit)? = null,
        merchant: MerchantWebVOF? = null,//因订阅页需要实时添加增加 其他场景未传
    ) {
        if (subOrNot) {
            // 取消订阅店铺确认弹窗
            ConfirmDialog2.Builder(if (ctx is Activity) ctx else ActivityStackManage.currentActivity())
                .setScene(1)
                .setTitle("Unfollow the store?")
                .setMessage("You will no longer receive updates from this store.")
                .setCancelButton(ctx.string(com.starblink.basic.style.R.string.un_follow)) { dialog, _ ->
                    // 取消订阅
                    dialog.dismiss()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.ConfirmDialog, SpmElementDef.DialogCancel
                            ), params = mapOf(
                                "merchantName" to (merchantName ?: ""),
                            )
                        )
                    )
                    refreshState?.invoke()
                    scope.launch {
                        val response = SkGqlClient.skMutation(
                            CancelSubscribeMerchantWebMutation(
                                ids = Optional.present(
                                    listOf(merchantId)
                                )
                            ),showDefaultLoading = false
                        )
                        resultCallback?.invoke(response?.data?.cancelSubscribeMerchantWeb == true)
                        if (response?.data?.cancelSubscribeMerchantWeb == true) {
                            //刷新订阅数据
                            val followStoreEvent = FollowStoreEvent(
                                merchantId,
                                !subOrNot,
                                merchant,
                                ActivityStackManage.isMainActivity()
                            )
                            FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT)
                                .post(followStoreEvent)

                            //跨进程通知
                            BridgeUtil.sendFlowBus(FlowConst.FOLLOW_STORE_EVENT, followStoreEvent)
                        }
                    }
                }
                .setSureButton("Keep") { dialog, _ ->
                    cancelNotCallback?.invoke()
                    dialog.dismiss()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.ConfirmDialog, SpmElementDef.DialogSure
                            ), params = mapOf(
                                "merchantName" to (merchantName ?: ""),
                            )
                        )
                    )
                }
                .create().show()
        } else {
            // 订阅店铺
            refreshState?.invoke()
            scope.launch {
                val response = SkGqlClient.skMutation(
                    SubscribeMerchantWebV2Mutation(
                        id = merchantId
                    ),
                    showDefaultLoading = false,
                    ifNeedHiddenLoading = false
                )
                val subSuccess = response?.data?.subscribeMerchantWebV2?.subStatus == true

                resultCallback?.invoke(subSuccess)
                if (subSuccess) {
                    //刷新订阅数据
                    val followStoreEvent = FollowStoreEvent(
                        merchantId, !subOrNot, merchant,
                        ActivityStackManage.isMainActivity()
                    )
                    FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT)
                        .post(followStoreEvent)
                    //跨进程通知
                    BridgeUtil.sendFlowBus(FlowConst.FOLLOW_STORE_EVENT, followStoreEvent)
                }

                handleDialogShowAfterSubscribeStore(
                    ctx,
                    response,
                    subSuccess,
                    scope
                )
            }
        }
    }

    /**
     * 处理订阅店铺后的弹窗显示
     * @notge
     */
    private fun handleDialogShowAfterSubscribeStore(
        ctx: Context, // 订阅是否成功
        response: ApolloResponse<SubscribeMerchantWebV2Mutation.Data>?,
        subSuccess: Boolean, // 订阅错误返回
        scope: CoroutineScope = MainScope(),
    ) {
        if (subSuccess) {
            // 订阅成功
            // 首次订阅店铺，显示订阅成功弹窗；否则，显示toast
//            if (response?.data?.subscribeMerchantWebV2?.firstSubOrNot == true) {
//                try {
//                    val fragmentActivity = if (ctx is FragmentActivity) ctx
//                    else ActivityStackManage.currentActivity() as FragmentActivity
//                    StoreFollowSuccessDialog().show(
//                        fragmentActivity.supportFragmentManager, "StoreFollowSuccessDialog"
//                    )
//                } catch (e: Exception) {
//                    YYLogUtils.e("StoreFollowSuccessDialog", throwable = e)
//                }
//            } else {
//                toastSuccess("Follow Successfully")
//            }

            //V1.5.2新逻辑
            doGuideLogin(
                2, scope, title = "Store Followed",
                imageResource = R.mipmap.icon_subscribe_success_store,
                emailTipResource = R.string.subscribe_success_email_store,
                noEmailTipResource = R.string.subscribe_success_no_email_store,
                remindMeKey = UserDataCenter.subscribeRemindMe_Store
            )
        } else {
            // 订阅失败，如果错误码为311014001，显示错误弹窗
            if (response?.findErrorCode(BaseApiCodeAndUrl.CODE_311014001) == true) {
//                val contentBinding =
//                    AddVSubFailBinding.inflate(
//                        LayoutInflater.from(ctx),
//                        null,
//                        false
//                    )
//                val subFailDialog =
//                    CustomDialog.Builder(if (ctx is Activity) ctx else ActivityStackManage.currentActivity())
//                        .create(contentBinding.root)
//                subFailDialog.show()
//                contentBinding.tryIt.click {
//                    subFailDialog.dismiss()
//                    ctx.navigation(path = RoutePage.Login.SING_IN)
//                }
                val activity = ActivityStackManage.currentActivity()
                if (activity is FragmentActivity) {
                    SubscribeFailDialog(
                        activity,
                        "Failed to Follow",
                        R.mipmap.icon_subscribe_fail_store,
                        R.string.subscribe_fail_store
                    ) {
                        ctx.navigation(path = RoutePage.Login.SING_IN)
                    }.show(activity.supportFragmentManager, "subscribeFail")
                }
            }
        }
    }

    /**
     * 订阅 or 取消订阅品牌
     */
    fun subscribeOrNotBrand(
        ctx: Context,
        subOrNot: Boolean,
        brandId: Any,
        scope: CoroutineScope = MainScope(),
        brand: BrandVOF? = null,        //因订阅页需要实时添加增加 其他场景未传
        cancelNotCallback: (() -> Unit)? = null,
        resultCallback: ((hasSub: Boolean) -> Unit)? = null,
    ) {
        Log.e("subscribeOrNot", subOrNot.toString())
        if (subOrNot) {
            // 取消订阅品牌
            ConfirmDialog2.Builder(if (ctx is Activity) ctx else ActivityStackManage.currentActivity())
                .setScene(1)
                .setTitle("Unfollow the Brand?")
                .setMessage("Unfollowing brand may cause you to miss out on discount updates for items under this brand.")
                .setCancelButton(ctx.string(com.starblink.basic.style.R.string.un_follow)) { dialog, _ ->
                    // 取消订阅
                    scope.launch {
                        val response = SkGqlClient.skMutation(
                            UnsubscribeBrandMutation(
                                brandIds = Optional.present(
                                    listOf(brandId)
                                )
                            ),showDefaultLoading = false
                        )
                        var reqSuccess = response?.data?.unsubscribeBrand == true

                        //mock数据
//                        reqSuccess=true

                        if (reqSuccess) {
                            resultCallback?.invoke(false)
                            val subscribeBrandEvent = SubscribeBrandEvent(brandId, false, brand)
                            //发送订阅品牌通知
                            FlowBus.with<SubscribeBrandEvent>(FlowConst.SUBSCRIBE_BRAND_EVENT)
                                .post(subscribeBrandEvent)
                        }
                    }
                    dialog.dismiss()
                }
                .setSureButton("Not now") { dialog, _ ->
                    cancelNotCallback?.invoke()
                    dialog.dismiss()
                }
                .create().show()
        } else {
            //订阅
            scope.launch {
                val response = SkGqlClient.skMutation(
                    SubscribeBrandMutation(
                        brandIds = Optional.present(
                            listOf(brandId)
                        )
                    ),
                    showDefaultLoading = false,
                    ifNeedHiddenLoading = false
                )

                var reqSuccess = response?.data?.subscribeBrand == true

                //mock数据
//                reqSuccess=true

                if (reqSuccess) {
                    resultCallback?.invoke(true)
                    val subscribeBrandEvent = SubscribeBrandEvent(brandId, true, brand)
                    //发送订阅品牌通知
                    FlowBus.with<SubscribeBrandEvent>(FlowConst.SUBSCRIBE_BRAND_EVENT)
                        .post(subscribeBrandEvent)
                    //订阅成功后绑定邮箱弹框逻辑
                    doGuideLogin(
                        1, scope, title = "Brand Followed",
                        imageResource = R.mipmap.icon_subscribe_success_brand,
                        emailTipResource = R.string.subscribe_success_email_brand,
                        noEmailTipResource = R.string.subscribe_success_no_email_brand,
                        remindMeKey = UserDataCenter.subscribeRemindMe_Brand
                    )
                } else {
                    // 订阅失败，如果错误码为311018001，显示错误弹窗
                    if (response?.findErrorCode(BaseApiCodeAndUrl.CODE_311018001) == true) {
                        val activity = ActivityStackManage.currentActivity()
                        if (activity is FragmentActivity) {
                            SubscribeFailDialog(
                                activity,
                                "Failed to Follow",
                                R.mipmap.icon_subscribe_fail_brand,
                                R.string.subscribe_fail_brand
                            ) {
                                ctx.navigation(path = RoutePage.Login.SING_IN)
                            }.show(activity.supportFragmentManager, "subscribeFail")
                        }
                    }
                }
            }
        }
    }

    /**
     * 是否引导登录
     * 1品牌 2 店铺 3 商品
     */
    private fun doGuideLogin(
        type: Int,
        scope: CoroutineScope = MainScope(),
        toastMsg: String = "Follow Successfully",
        title: String,
        imageResource: Int = R.mipmap.icon_subscribe_success_brand,
        noEmailTipResource: Int,
        emailTipResource: Int,
        remindMeKey: String,
        subscribeNextSuccess: (() -> Unit)? = null
    ) {
        val mActivity = ActivityStackManage.currentActivity()
        if (!UserDataCenter.isLogin()) {
            //未登录 调用接口是否需要引导登录
            scope.launch {
                val response = SkGqlClient.skQuery(
                    MyDeviceSubscribeStaticQuery(type),
                    showDefaultLoading = false,
                    ifNeedHiddenLoading = false
                )
                var reqSuccess =
                    response?.data?.myDeviceSubscribeStatic?.mySubscribeStaticRespF?.needLogin == true

                //mock数据
//                reqSuccess=true

                if (reqSuccess) {
                    LoginCheckInterceptor.check2Login(mActivity,ifMustCallBack = true) {
                        subscribeNext(
                            mActivity,
                            scope,
                            toastMsg,
                            title,
                            imageResource,
                            noEmailTipResource,
                            emailTipResource,
                            remindMeKey,
                            subscribeNextSuccess
                        )
                    }
                } else {
                    subscribeNext(
                        mActivity,
                        scope,
                        toastMsg,
                        title,
                        imageResource,
                        noEmailTipResource,
                        emailTipResource,
                        remindMeKey,
                        subscribeNextSuccess
                    )
                }
            }
        } else {
            subscribeNext(
                mActivity,
                scope,
                toastMsg,
                title,
                imageResource,
                noEmailTipResource,
                emailTipResource,
                remindMeKey,
                subscribeNextSuccess
            )
        }
    }

    /**
     * subscribeNextSuccess 弹框消失回调
     */
    private fun subscribeNext(
        activity: Activity,
        scope: CoroutineScope = MainScope(),
        toastMsg: String = "Follow Successfully",
        title: String,
        imageResource: Int = R.mipmap.icon_subscribe_success_brand,
        noEmailTipResource: Int,
        emailTipResource: Int,
        remindMeKey: String,
        subscribeNextSuccess: (() -> Unit)? = null
    ) {

        if (UserDataCenter.getSubscribeRemindMe(remindMeKey)) {
            //调接口获取是否已经绑定邮箱
            scope.launch {
                val responseUserInfo = SkGqlClient.skQuery(
                    FetchSubscriptionSettingQuery(
                    ),
                    showDefaultLoading = false
                )
                val subscriptionSettingRespF =
                    responseUserInfo?.data?.fetchSubscriptionSetting?.subscriptionSettingRespF
                subscribeSuccessDialog(
                    activity,
                    subscriptionSettingRespF?.email,
                    subscriptionSettingRespF?.registerEmail,
                    title,
                    imageResource,
                    noEmailTipResource,
                    emailTipResource,
                    remindMeKey,
                    subscribeNextSuccess
                )
            }
        } else {
            subscribeNextSuccess?.invoke()
            toastSuccess(toastMsg)
        }

    }

    /**
     * 订阅成功弹框 两个状态 已绑定未绑定 本地记录是否再次提醒我弹框
     * email 已绑定的邮箱
     * registerEmail 注册邮箱
     */
    private fun subscribeSuccessDialog(
        activity: Activity,
        email: String?,
        registerEmail: String?,
        title: String,
        imageResource: Int,
        noEmailTipResource: Int,
        emailTipResource: Int,
        remindMeKey: String,
        subscribeNextSuccess: (() -> Unit)? = null
    ) {
        //订阅弹框
        if(FastUtil.isFast(1000)){
            return
        }
        if (activity is FragmentActivity) {
            //应该所有的activity都是fragmentActivity
            SubscribeDialog(
                activity,
                email,
                registerEmail,
                title,
                imageResource,
                noEmailTipResource,
                emailTipResource,
                remindMeKey,
                subscribeNextSuccess,
            ).show(activity.supportFragmentManager, "subscribe")
        }
    }

    /**
     * 登录后设置订阅邮箱
     */
    fun subscribeEmailAfterLogin() {
        if (UserDataCenter.isLogin()) {
            MainScope().launch {
                val responseUserInfo = SkGqlClient.skQuery(
                    FetchSubscriptionSettingQuery(
                    ),
                    showDefaultLoading = false
                )
                val subscriptionSettingRespF =
                    responseUserInfo?.data?.fetchSubscriptionSetting?.subscriptionSettingRespF
                subscriptionSettingRespF?.let {
                    val subscribeEmail = UserDataCenter.getSubscribeEmail()
                    if (CheckUtil.isEmpty(it.email) && !CheckUtil.isEmpty(subscribeEmail)) {
                        MainScope().launch {
                            SkGqlClient.skMutation(
                                ModifySubscriptionSettingMutation(
                                    req = SubscriptionSettingReq(
                                        email = subscribeEmail.optional()
                                    )
                                )
                            )?.run {
                                if (data?.modifySubscriptionSetting == true) {
                                    UserDataCenter.putSubscribeEmial("")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}